<template>
<div class="content">
  <el-card>
    <div slot='header' class='text'>
      <span v-if='$route.query.id'>试题修改</span>
      <span v-else>试题录入</span>
    </div>
    <div class="content">
      <el-form
        :model='ruleForm'
        label-width="100px"
        class="rulesForm"
        :rules='rules'
        ref='rulesForm'>
          <el-form-item label="学科:" prop='subjectID'>
            <el-select class='select' @change='getdirectorys' v-model='ruleForm.subjectID' placeholder="请选择">
              <el-option
              v-for='item in subject'
              :key='item.id'
              :label="item.label"
              :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop='catalogID'>
            <el-select class='select' v-model='ruleForm.catalogID' placeholder="请选择">
              <el-option v-for='item in directorys' :key='item.value' :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop='enterpriseID'>
            <el-select class='select' v-model='ruleForm.enterpriseID' placeholder="请选择">
              <el-option v-for='item in companys' :key='item.id' :label="item.company" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
           
          <el-form-item label="城市:" prop='city'>
            <el-col :span="8.5">
              <el-form-item >
                <el-select class='selectprovince' v-model='ruleForm.province' @change='handlepro' placeholder="请选择" >
                  <el-option v-for='(item, index) in cityselect.province' :key='index' :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" >
              <el-form-item >
                <el-select v-model='ruleForm.city' placeholder="请选择" >
              <el-option v-for='(item, index) in cityselect.city' :key='index' :label="item" :value="item"></el-option>
            </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
    
          <el-form-item label="方向:" prop='direction'>
            <el-select class='select' v-model='ruleForm.direction' placeholder="请选择">
              <el-option v-for='item in direction' :key='item.id' :label="item.direction" :value="item.direction"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop='questionType'>
             <!-- 单选框 -->
            <el-radio
            v-model="ruleForm.questionType"
            :label="item.value"
            v-for='item in questionType'
            :key='item.value'>{{item.label}}</el-radio>
          </el-form-item>
          <el-form-item label="难度:" prop='difficulty'>
             <!-- 单选框 -->
            <el-radio v-model="ruleForm.difficulty" :label="item.value" v-for='item in difficulty' :key='item.value'>{{item.label}}</el-radio>
          </el-form-item>
          <el-form-item label='题干:' prop='question' >
            <quill-editor ref="text" v-hljs v-model="ruleForm.question" class="myQuillEditor" :options="editorOption" style="width:100%;height:200px;marginBottom:50px"/>
          </el-form-item>
          <el-form-item label='选项:' prop='option' v-if='ruleForm.questionType === 1'>
             <el-radio-group v-model="code" > 
             <div class='radio' v-for='(item, index) in this.ruleForm.options'
             :key='index'>
               <el-radio class='answer'
               :label='item.code'
               @change='changecode(index)'>
               </el-radio>
               <i class="el-icon-circle-close"></i>
                <el-input v-model='item.title' >
                </el-input>
                <el-upload
                  class="upload-demo"
                  action="https://www.liulongbin.top:8888/api/private/v1/upload"
                  drag
                  list-type="picture"
                  :on-success='(response, file, fileList) => handlesuccess(response, file, fileList,index)'
                  :on-preview="handlePreview"
                  :headers='headersobj'
                >
                  上传图片
                </el-upload>   
             </div>
             </el-radio-group> 
              <div class='button'>
               <el-button type='danger' @click='addradio' disabled>+ 增加选项与答案</el-button>
               </div>
          </el-form-item>   
          <el-form-item label='选项:' prop='option' v-else-if='ruleForm.questionType === 2'>
             <el-checkbox-group v-model="code" >
               <div class='checkbox'
               v-for="(item, index) in ruleForm.options"
               :key="index">
                <el-checkbox 
                  class='anwser'
                  :label="item.code"
                  @change='changecode(index)'>
                </el-checkbox> 
                <i class="el-icon-circle-close"></i>
                <el-input v-model='item.title' >
                </el-input>
                <el-upload
                  class="upload-demo"
                  action="https://www.liulongbin.top:8888/api/private/v1/upload"
                  drag
                  list-type="picture"
                  :on-success='(response, file, fileList) => handlesuccess(response, file, fileList,index)'
                  :on-preview="handlePreview"
                  :headers='headersobj'
                >
                  上传图片
                </el-upload>   
               </div> 
             </el-checkbox-group> 
             <div class='button'>
               <el-button type='danger' @click='addradio' >+ 增加选项与答案</el-button>
               </div>
          </el-form-item>
          <el-form-item class='videoparse' label='解析视频:'>
            <el-input v-model='ruleForm.videoURL'></el-input>
          </el-form-item>
          <el-form-item class='answerparse' label='答案解析:' prop='answer '>
            <quill-editor ref="text" v-hljs v-model="ruleForm.answer" class="myQuillEditor" :options="editorOption" style="width:100%;height:200px;marginBottom:50px" />
          </el-form-item>
          <el-form-item class='title' label='题目备注:'>
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="ruleForm.remarks">
            </el-input>
          </el-form-item>
          <el-form-item class='tags' label='试题标签:'>
            <el-select class='select' multiple v-model='ruleForm.tags' placeholder="请选择">
              <el-option v-for='item in tagslist' :key='item.value' :label="item.label" :value="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-button v-if='$route.query.id' class='sureup' type='success' @click='ConfirmSubmit'>确认修改</el-button>
          <el-button v-else class='sureup' type='primary' @click='ConfirmSubmit'>确认提交</el-button>
      </el-form>
    </div>
  </el-card>

  <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="100%">
      <img :src="img" alt="" class='previewImg'>
    </el-dialog>
</div>
</template>

<script>
import { simple as subject } from "@/api/hmmm/subjects"
import { simple as directoryslist } from "@/api/hmmm/directorys"
import { list as companyslist } from '@/api/hmmm/companys'
import { list as questionslist, add, detail, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as tagslist } from '@/api/hmmm/tags'
import { questionType, difficulty } from '@/api/hmmm/constants' 
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/tomorrow.css'


export default {
  name: 'questionsNew',
  data () {
    return {
      ruleForm: { // 验证规则内容
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 市级
        direction: '', // 方向
        questionType: '', // 题型单选框
        difficulty: '', // 难度单选框
        answer: '', // 答案解析
        question: '', // 题干内容 -----
        options: [], // 选项内容
        videoURL: '', // 视频解析
        remarks: '', // 题目备注
        tags: null, // 试题标签
        city: '',
      },
       // 富文本框
       editorOption: {
         // 富文本编辑器配置
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ list: "ordered" }, { list: "bullet" }], //列表
            ["code-block", "blockquote"], //引用，代码块
            ["image", "link"], //上传图片、上传视频
          ],
          syntax: {
            highlight: (text) => hljs.highlightAuto(text).value,
          },
        },
        theme: "snow"
       }, // 编辑器选项
      rules: {
        subjectID:[
          { required: true, message: '请选择科目', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        questionType: [
           { required: true, message: '请选择', trigger: 'change' }
        ],
        difficulty: [
           { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      subject: [], // 科目列表
      directorys: [], // 目录列表
      companys: [], // 企业列表
      direction: [], // 方向列表
      cityselect: { // 城市列表
        province: [],
        city: []
      },
      tagslist: [], // 标签列表
      a: ['A', 'B', 'C', 'D'],
      b: ['D', 'E', 'F', 'G'],
      // 图片上传的headers请求头
      headersobj: {
        Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE1OTU4NTEyNTcsImV4cCI6MTU5NTkzNzY1N30.KPbQtL80ulwrdDiJhm0-uvQazYsT2VWZdqqfDdg72uY"
      },
      previewVisible: false,
      img: '',
      questionType,
      difficulty,
      title: '',
      code:[],
     // 上个页面传递过来的ID
      lastid: ''
    }
  },
  components: {
    quillEditor
  },
  created() {
    this.getsubject()
    // this.getdirectorys()
    this.getcompanys()
    this.getdirection()
    this.getprovinces()
    // this.gettags()
    for(var i=0; i<4; i++) {
       this.ruleForm.options.push({
       title: '',
       img: '' ,
       isRight: 0,
       code: this.a[i]
     })
    }
    // console.log(this.ruleForm.options)

    // 获取跳转页面的路径ID
    this.lastid = this.$route.query.id
    // console.log(this.lastid)
    // console.log(this.$route)

    if (this.lastid) {
      this.getquestiontext()
    }
  },
  methods: {
    changecode (index) {
      this.ruleForm.options[index].isRight = 1
      // console.log(this.ruleForm.options[index].title)
    },
    // 学科列表请求
    async getsubject () {
      try {
        const { data } = await subject()
        this.subject = data
        // console.log(data)
      } catch (err) {
        this.message('获取学科列表失败')
      }
    },
    // 目录列表请求
    async getdirectorys () {
      // console.log(this.ruleForm.subjectID);
       try {
        const { data } = await directoryslist({subjectID:this.ruleForm.subjectID})
        this.directorys = data
        // console.log(data)
        // console.log(this.directorys)
      } catch (err) {
        this.$toast.fail('获取学科列表失败')
      }
      // 获取标签
       try {
        const { data } = await tagslist({subjectID:this.ruleForm.subjectID})
        this.tagslist = data
        // console.log(data)
        // console.log(this.tagslist)
      } catch (err) {
        this.$toast.fail('获取学科列表失败')
      }
    },
    // 企业列表请求
    async getcompanys () {
       try {
        const { data } = await companyslist()
        this.companys = data.items
        console.log(data)
        // console.log(this.companys)
      } catch (err) {
        this.$toast.fail('获取学科列表失败')
      }
    },
    // 方向列表请求
    async getdirection () {
       try {
        const { data } = await questionslist()
        this.direction = data.items
        // console.log(data)
        // console.log(this.direction)
      } catch (err) {
        this.$toast.fail('获取学科列表失败')
      }
    },
    // 获取市
    getprovinces () {
      this.cityselect.province = provinces()
      // console.log(this.cityselect.province)
    },
    // 获取区
    handlepro (e) { // e表示在市级框中选择到的数据
      this.cityselect.city = citys(e)
      // console.log(this.cityselect.city)
    },
    addradio () { // 点击添加选项
      let i = 0
      i++
      this.a.push(this.b[i])
      // console.log(this.a)
    },
    // 上传图片
    // 图片上传成功处理的事件
    handlesuccess (response, file, fileList, index) {
      // 获取图片地址
      const picInfo = response.data.url
      this.img = picInfo
      // 把picInfo的字符串放到 ruleForm.options[对应索引].img = picInfo
      this.ruleForm.options[index].img = picInfo
      // console.log(picInfo)
      // console.log(response)
      // console.log(file)
      // console.log(fileList)
    },
    // 图片预览
    handlePreview (file) {
      this.img = file.response.data.url
      this.previewVisible = true
    },
    
    // 确认提交
    ConfirmSubmit () {
      this.$refs.rulesForm.validate(async valid => {
        const obj =JSON.parse(JSON.stringify(this.ruleForm))
        obj.tags = obj.tags.join('')
        obj.difficulty = obj.difficulty + ''
        obj.questionType = obj.questionType + ''
        for(var i=0; i<this.code.length; i++) {
          if (obj.options[i].code === this.code[i]) {
            obj.options[i].isRight = 1
          }
        }
        // console.log(obj)
        if (valid) {
          // const a = await add (obj)
          let a
          if (this.$route.query.id) {
            //  for(var i=0; i<this.code.length; i++) {
            //    if (obj.options[i].code = this.code[i]) {
            //      obj.options[i].isRight = 1
            //      obj.tags = obj.tags.split(',')
            //      obj.difficulty = obj.difficulty * 1
            //      obj.questionType = obj.questionType * 1
            //      this.ruleForm= obj
            //    }
            //  }
            a = await update (obj)
            if (a.status === 200) {
              this.$router.go(-1)
              this.$message.success('修改成功')
            }
          } else {
            a = await add (obj)
            this.$router.push('/questions/list')
            this.$message.success('添加成功')
          }
          // if (a.status === 200) {
          //   if (this.$route.query.id){
             
          //   } else {
             
          //   }
          }
          // console.log(a)
        // } else {
        //   return
        // }
      })
    },

    // 获取基础题库详情
    async getquestiontext () {
      try {
        console.log(this.lastid)
        const { data } = await detail({ id: this.lastid })
        const obj =JSON.parse(JSON.stringify(data))
        obj.tags = obj.tags.split(',')
        obj.difficulty = obj.difficulty * 1
        obj.questionType = obj.questionType * 1
        this.ruleForm = obj
        // for (var i=0; i<this.ruleForm.options.length; i++) {
        //   if (this.ruleForm.options[i].isRight === 1) {
        //     this.code.push(this.ruleForm.options[i].code)
        //   }
        // }
        this.ruleForm.options.forEach (item => {
          if (item.isRight === 1) {
            this.code.push(item.code)
          }
        })
        if (this.ruleForm.questionType === 1) {
          this.code = this.code.join('')
        }
        // console.log(this.code)
      } catch (err) {
        // console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='less'>
.el-card {
  .content {
    .select {
      width: 400px
    }
    .selectprovince {
      margin-right: 10px;
    }
    /deep/.el-form-item__content{
      position: relative;
      .el-checkbox-group {
        .checkbox {
          position: relative;
          .el-icon-circle-close {
            position: absolute;
           top: -13px;
           left: 550px;
            z-index: 1;
            font-size: 13px;
          }
          .el-upload-list--picture .el-upload-list__item {
            height: 70px;
            width: 70px;
            position: absolute;
            top: -21px;
            left: 574px;
          }
          .el-upload-list--picture .el-upload-list__item-thumbnail {
            height: 49px;
            }
          .el-input {
            width: 400px !important;
            margin-left: 10px;
          }
          .upload-demo {
            .el-upload-dragger {
              width: 100px;
              height: 60px;
              position: absolute;
              top: -8px;
              left: 457px;
            }
          }
        }
      }
      .el-radio-group {
        .radio {
          position: relative;
          .el-radio {
            margin-right: 0px !important;
          }
          .el-icon-circle-close {
            position: absolute;
           top: -13px;
           left: 550px;
            z-index: 1;
            font-size: 13px;
          }
          .el-upload-list--picture .el-upload-list__item {
            height: 70px;
            width: 70px;
            position: absolute;
            top: -21px;
            left: 574px;
          }
          .el-upload-list--picture .el-upload-list__item-thumbnail {
            height: 49px;
            }
          .el-input {
            width: 400px !important;
            margin-left: 10px;
            margin-bottom: 40px;
          }
          .upload-demo {
            .el-upload-dragger{
              width: 100px;
              height: 60px;
              position: absolute;
              top: -8px;
              left: 457px;
            }
          }
        }
      }
    }
    // .answerparse, .videoparse, .title, .tags{
    //   padding-left: 30px !important;
    // }
    .videoparse, .title, .tags{
      width: 500px;
    }
    .sureup {
      margin-left: 60px;
    }
  }
}
</style>
